package com.tahado.service;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;

import org.apache.commons.codec.binary.Base64;

 

public class SignedRequestParser {
	 //Facebook App info
  public  static final String fbSecretKey = "f119abb89ff79ee29a012d80600548fa";
  public  static final String fbAppId = "114695075294742";
  public  static final String fbCanvasPage = "http://apps.facebook.com/114695075294742/";
  public  static final String fbCanvasUrl = "http://hadaya1001.appspot.com/afterAuthrized.jsp";
public static JSONObject parse(String signedRequestParam) throws UnsupportedEncodingException, InvalidKeyException, NoSuchAlgorithmException{
    //parse signed_request
  

        //it is important to enable url-safe mode for Base64 encoder 
        Base64 base64 = new Base64();

        //split request into signature and data
        String[] signedRequest = signedRequestParam.split("\\.", 2);

        //parse signature
        byte [] signatureBytes = base64.decode(signedRequest[0].getBytes("UTF-8"));
        System.out.println(Arrays.toString(base64.decode(signedRequest[0].getBytes("UTF-8"))));
        String sig = new String(signatureBytes);

        //parse data and convert to json object
        JSONObject data = (JSONObject)JSONSerializer.toJSON(new String(base64.decode(signedRequest[1].getBytes("UTF-8"))));

        //check signature algorithm
        if(!data.getString("algorithm").equals("HMAC-SHA256")) {
            //unknown algorithm is used
            throw new NoSuchAlgorithmException();
        }

        //check if data is signed correctly
        if(!hmacSHA256(signedRequest[1], fbSecretKey).equals(sig)) {
            //signature is not correct, possibly the data was tampered with
            throw new InvalidKeyException();
        }
        return data;


}


//HmacSHA256 implementation 
private static String hmacSHA256(String data, String key) throws UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeyException  {
    SecretKeySpec secretKey = new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA256");
    Mac mac = Mac.getInstance("HmacSHA256");
    mac.init(secretKey);
    byte[] hmacData = mac.doFinal(data.getBytes("UTF-8"));
    System.out.println(Arrays.toString(hmacData));
    return new String(hmacData);
}
}
